package com.faxsun.core.service.fulfillment;

import org.broadleafcommerce.core.order.domain.FulfillmentGroup;
import org.broadleafcommerce.core.order.service.call.FulfillmentGroupItemRequest;
import org.broadleafcommerce.core.order.service.call.FulfillmentGroupRequest;
import org.broadleafcommerce.core.pricing.service.exception.PricingException;
import org.springframework.transaction.annotation.Transactional;

public class FSFulfillmentGroupServiceImpl extends org.broadleafcommerce.core.order.service.FulfillmentGroupServiceImpl{

	 @Override
	    @Transactional("blTransactionManager")
	    public FulfillmentGroup addFulfillmentGroupToOrder(FulfillmentGroupRequest fulfillmentGroupRequest, boolean priceOrder) throws PricingException {
	        FulfillmentGroup fg = fulfillmentGroupDao.create();
	        fg.setAddress(fulfillmentGroupRequest.getAddress());
	        fg.setOrder(fulfillmentGroupRequest.getOrder());
	        fg.setPhone(fulfillmentGroupRequest.getPhone());
	        fg.setFulfillmentOption(fulfillmentGroupRequest.getOption());
	        fg.setType(fulfillmentGroupRequest.getFulfillmentType());

	        fg=save(fg);
	        
	        for (int i = 0; i < fulfillmentGroupRequest.getFulfillmentGroupItemRequests().size(); i++) {
	            FulfillmentGroupItemRequest request = fulfillmentGroupRequest.getFulfillmentGroupItemRequests().get(i);
	            request.setFulfillmentGroup(fg);
	            request.setOrder(fulfillmentGroupRequest.getOrder());
	            
	            boolean shouldPriceOrder = (priceOrder && (i == (fulfillmentGroupRequest.getFulfillmentGroupItemRequests().size() - 1)));
	            fg = addItemToFulfillmentGroup(request, shouldPriceOrder);
	        }

	        return fg;
	    }
}
